import pyautogui
import time
import win32com.client
import os
import pythoncom

import core.team_comm  as team_comm
import team.invite_team as invite_team
import runnings.runnings as running

window_left = 0
window_wight = 0
window_top = 0
window_height = 0
game_window_left = 0
game_window_wight = 0
game_window_top = 0
game_window_height = 0




class Script:
    def __init__(self):
        pythoncom.CoInitialize()  # 初始化 COM
        self.ret_my_info = None
        self.dm = win32com.client.Dispatch("dm.dmsoft")
        print("大漠插件版本：", self.dm.Ver())
        script_dir = os.path.dirname(os.path.abspath(__file__))
        print("当前目录", script_dir)
        self.dm.SetPath(os.path.join(script_dir))

        # 关键修改1：强制设置绝对路径
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        self.dm.SetPath(self.script_dir)

        # 关键修改2：显式加载字库文件
        self.font_file = os.path.join(self.script_dir, "game_font.txt")
        if os.path.exists(self.font_file):
            # 3.1232版本必须用SetDict加载字库文件
            ret = self.dm.SetDict(0, self.font_file)
            print(f"字库加载状态: {'成功' if ret == 1 else '失败'}")
        else:
            with open(self.font_file, "w", encoding="gbk") as f:
                f.write("[game_font]\n")
            print("新建空字库文件")

    def find_game_window(self, partial_title):

        try:
            for i in range(100):
                # 获取所有包含部分标题的窗口
                windows = pyautogui.getWindowsWithTitle(partial_title)

                if windows:
                    print(f"找到 {len(windows)} 个匹配窗口:")
                    for i, win in enumerate(windows, 1):
                        print(f" 完整标题: '{win.title}'")

                    # 返回第一个匹配的窗口
                    return windows[0]
                else:
                    print(f"未找到标题包含 '{partial_title}' 的窗口，重试第'{i + 1}'次...")
                    time.sleep(1)

            print(f"未找到标题包含 '{partial_title}' 的窗口")
            return None
        except Exception as e:
            print(f"查找窗口时出错: {e}")
        return None

    # 游戏启动器
    def action_controller(self):

        windows = self.find_game_window("Launcher")  # 替换为你的游戏窗口部分标题
        if windows:
            print(f"找到启动器窗口: {windows.title}")
            print(f"启动器窗口尺寸: {windows.width}x{windows.height}")
            print(f"启动器窗口位置: ({windows.left}, {windows.top})")
            windows.activate()
            time.sleep(5)
            window_left = windows.left - 10
            window_wight = windows.width
            window_top = windows.top - 10
            window_height = windows.height

        else:
            print("未找到启动器窗口")

        #  点击启动游戏按钮
        pyautogui.moveTo(x=(window_left + (window_wight * 0.75)),
                         y=(window_top + (window_height * 0.77)))
        time.sleep(1)
        pyautogui.click()

    # 点击进入游戏
    def click_run_game(self):
        # 查找游戏窗口
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:

            print(f"找到游戏窗口: {game_window.title}")
            print(f"游戏窗口尺寸: {game_window.width}x{game_window.height}")
            print(f"游戏窗口位置: ({game_window.left}, {game_window.top})")
            game_window.activate()
            time.sleep(5)
            pyautogui.keyDown("space")
            pyautogui.keyUp("space")
            time.sleep(1)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            #  点击进入游戏按钮
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.5)),
                             y=(game_window_top + (game_window_height * 0.7)))
            time.sleep(1)
            pyautogui.click()
            time.sleep(5)
            pyautogui.keyDown("space")
            pyautogui.keyUp("space")

            time.sleep(5)
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.95)),
                             y=(game_window_top + (game_window_height * 0.97)))
            time.sleep(1)
            pyautogui.click()



        else:
            print("未找到游戏窗口")

    # 开始游戏
    def star_play(self):  # 查找游戏窗口
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            time.sleep(2)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            #  点击进入游戏按钮
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.15)),
                             y=(game_window_top + (game_window_height * 0.07)))
            time.sleep(1)

            for i in range(2):
                pyautogui.click()
                time.sleep(0.2)

            # 选择模式
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.9)),
                             y=(game_window_top + (game_window_height * 0.75)))
            time.sleep(1)

            pyautogui.click()

            time.sleep(2)

            # 选择人机
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.9)),
                             y=(game_window_top + (game_window_height * 0.75)))
            time.sleep(1)
            pyautogui.click()




        else:
            print("未找到游戏窗口")

    # 关闭游戏
    def off_or_run_game(self, run_or_off):
        steam_windows = self.find_game_window("Steam")
        if steam_windows:
            steam_windows.activate()
            click_x = steam_windows.left + 320
            click_y = steam_windows.top + 350
            pyautogui.moveTo(click_x, click_y)
            time.sleep(1)
            pyautogui.click()

            if run_or_off == 0:
                pyautogui.moveTo(click_x + 150, click_y + 30)
                time.sleep(1)
                pyautogui.click()
                time.sleep(20)

        else:
            print("未找到Steam窗口")







    def get_pic(self):

        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            time.sleep(1)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

        x1 = game_window_left + 30
        y1 = game_window_top + 50
        x2 = game_window_left + 150
        y2 = game_window_top + 75
        text = self.dm.Capture(x1, y1, x2, y2, "test.bmp")

    # 从steam开始登录游戏
    def start_controller(self):
        # Steam开始游戏
        self.off_or_run_game(1)
        time.sleep(30)
        # 启动器启动
        self.action_controller()
        time.sleep(60)
        # 开始游戏
        self.click_run_game()
        time.sleep(5)


    # 组队控制
    def team_controller(self):

        team = team_comm.TeamCommander()
        # 重置 status = 0
        team.set_init_status()

        # 查询我的信息
        self.ret_my_info = team.load_my_info()

        print(f"我的信息：{self.ret_my_info}")

        # 判断是否是队长
        if self.ret_my_info and self.ret_my_info["is_leader"] == 1:
            my_team_id = self.ret_my_info['team_id']
            self.leader_controller(team,my_team_id)


    # 邀请队友 并 通知队友
    def leader_controller(self,team,my_team_id):

        # 选择模式
        self.star_play()

        # 邀请队友
        my_team_info = team.load_team_info(my_team_id)
        if my_team_info:
            invite_team.invite_team(my_team_info)

        time.sleep(5)

        # 查询队员是否准备就绪
        self.check_all_ready(team,my_team_id ,my_team_info)

    def check_all_ready(self,team,my_team_id,my_team_info):
        wait_time = 60
        # 获取当前秒值
        this_time = int(time.time())
        # 延迟 wait_time后开始游戏
        start_time = this_time + wait_time
        my_team_ready = team.load_team_ready(my_team_id)
        if len(my_team_ready) >= 5:
            # 通知所有成员开始游戏
            for one in my_team_info:
                ip = one['ip']
                team.send_start_time(ip, start_time)

        new_time = int(time.time())
        sleep_time = start_time - new_time
        self.after_invite_start_game(sleep_time)


    # 完成组队后队长开始游戏
    def after_invite_start_game(self,sleep_time):
        time.sleep(sleep_time)
        # 识别是不是已经进入选择英雄阶段
        for i in range(100):
            is_hero_pick_flag = self.is_hero_pick()
            if is_hero_pick_flag:
                self.controller()
            # 如果不是延迟
            time.sleep(1)
            print(f"重新判断，是否是选英雄阶段，第{i}次")


    # 选择英雄阶段 确认
    def is_hero_pick(self):
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            time.sleep(0.5)

            x1 = (game_window_left + (game_window_wight * 0.01))
            y1 = (game_window_top + (game_window_height * 0.085))
            x2 = (game_window_left + (game_window_wight * 0.025))
            y2 = (game_window_top + (game_window_height * 0.1))


            color = "ffdc31-050505"
            # # 3.1232版本OCR参数：区域坐标 + 颜色 + 相似度
            text = self.dm.Ocr(x1, y1, x2, y2, color, 0.8)
            if text and text == '选择英雄阶段':
                print(f"识别结果: {text}")
                return True
            else:
                print("识别失败！")
                return False

    def controller(self):
        # 选择英雄
        self.hero_pick()
        time.sleep(20)

        # 识别地图和攻防 选择走位
        self.check_map_direction()
        time.sleep(1)


    # 选择英雄
    def hero_pick(self):
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            time.sleep(1)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            # 点击开始游戏
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.85)),
                             y=(game_window_top + (game_window_height * 0.85)))
            time.sleep(1)
            pyautogui.click()
            time.sleep(20)

            #  选择英雄
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.7)),
                             y=(game_window_top + (game_window_height * 0.15)))
            time.sleep(1)
            pyautogui.click()

            # 获取序列
            ordinal = self.ret_my_info['order_num']
            print(f"{self.ret_my_info['game_name']}所在的序列{ordinal}")
            if ordinal > 0:
                for i in range(ordinal*2):
                    pyautogui.scroll(1)
                time.sleep(0.5)
            for i in range(10):
                pyautogui.click()
                time.sleep(0.2)
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.85)),
                             y=(game_window_top + (game_window_height * 0.7)))
            pyautogui.click()


    # 确定地图和攻防方
    def check_map_direction(self):

        ret_map =self.recognize_text_left_top()
        r = running.Runnings()
        if ret_map:
            if ret_map ==  "阻止世界树抽汁":
                r.running_11()

            elif ret_map == "摧毁洛基的世界":
                r.running_12()

            elif ret_map == "阻止蜘蛛零回到":
                r.running_311()

            elif ret_map == "帮助蜘蛛零回到":
                r.running_312()

            elif ret_map == "帮助织网大师强":
                r.running_411()

            elif ret_map == "帮助蜘蛛零修复":
                r.running_412()

            elif ret_map == "阻止巴斯特精神":
                r.running_611()

            elif ret_map == "帮助巴斯特精神":
                r.running_612()

            elif ret_map == "阻止纳尔精华":
                r.running_711()

            elif ret_map == "护送纳尔精华":
                r.running_712()

            elif ret_map == "阻止赫尔比扫描":
                r.running_911()

            elif ret_map == "帮助赫尔比扫描":
                r.running_912()

            elif ret_map == "使用蒙特西法则":
                r.running_1011()

            elif ret_map == "进入德古拉城堡":
                r.running_1012()

            elif ret_map == "阻止克拉科与阿":
                r.running_1211()

            elif ret_map == "帮助克拉科与阿":
                r.running_1212()

            else:
                self.out_game()
        else:
            self.out_game()






    # 进游戏后识别左上角字体 第一标题
    def recognize_text_left_top(self):

        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            time.sleep(1)
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

        x1 = game_window_left + 30
        y1 = game_window_top + 50
        x2 = game_window_left + 150
        y2 = game_window_top + 75
        """
        识别指定区域的文字
        :return: 识别结果字符串
        """
        color = "ffffff-202020|aaadaf-202020|dedfdf-202020"
        # 3.1232版本OCR参数：区域坐标 + 颜色 + 相似度
        text = self.dm.Ocr(x1, y1, x2, y2, color, 0.8)
        if text:
            print(f"识别结果: {text}")
            return text
        else:
            print("识别失败！")
            return ""


    # 遇到无法识别的地图，退出游戏 并重新组队
    def out_game(self):
        game_window = self.find_game_window("Marvel Rivals")
        if game_window:
            game_window.activate()
            game_window_left = game_window.left - 10
            game_window_wight = game_window.width
            game_window_top = game_window.top - 10
            game_window_height = game_window.height

            time.sleep(1)
            pyautogui.keyDown('esc')
            time.sleep(0.2)
            pyautogui.keyUp('esc')
            time.sleep(0.5)

            # 点击推出房间
            pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.5)),
                             y=(game_window_top + (game_window_height * 0.7)))
            time.sleep(1)
            pyautogui.click()

        time.sleep(10)
        # 重新开始组队
        self.team_controller()



# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print(pyautogui.KEYBOARD_KEYS)
    dm = Script()
    dm.team_controller()

    # try:
    #     while True:
    #         time.sleep(1)
    #
    #         # 关闭游戏
    #         # off_or_run_game(0)
    # except KeyboardInterrupt:
    #     print("\n监控已停止")
